#include "guish.hpp"

int main(int argc, char **argv)
{
	//setAlwaysTrace(true);
	
	handleArgs(argc, argv);
	
	eventManager = new EventManager();
	ioManager = new IOManager(eventManager);
	processManager = new ProcessManager();
	ptyManager = new PtyManager();
	clientConnection = new ClientConnection(0, 1);
	
	shell = new Shell(clientConnection);
	clientConnection->setInteractiveShell(shell);
	
	setFileAsync(0, true);
	setFileAsync(1, true);
	makeTermRaw(0);
	
	shell->initialize();
	eventLoop(clientConnection);
}

void eventLoop(ClientConnection *client)
{
	while(client->isConnected())
	{
		if(ioManager->doIO(false, 1)) continue;
		if(ioManager->doIO(false, 2)) continue;
		processManager->checkChildren();
		ioManager->doIO(true, 3);
	}
}

void handleEvent(Event *event)
{
	if(dynamic_cast<SignalEvent*>(event))
	{
		processManager->checkChildren();
	}
	else if(dynamic_cast<JobFinishedEvent*>(event))
	{
		JobFinishedEvent *jobFinished = (JobFinishedEvent*)event;
		shell->finishJob(jobFinished->id, jobFinished->pty, jobFinished->result, jobFinished->state);
	}
	else if(dynamic_cast<ExitShellEvent*>(event))
	{
		shell->doExit();
	}
	else if(dynamic_cast<CrashTestEvent*>(event))
	{
		*((char*)0) = 0;
	}
}

